import axios from 'axios'
import {config} from '@/config'
const Qs = require('qs')

export const weiXinPay = (params, fn, cancelFn) => {
  params = Qs.stringify(params)
  axios.post(config.wxPay, params).then(({data}) => {
      if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      }else {
        onBridgeReady()
      }
      
      function onBridgeReady() {
        const params = {
          "appId": config.appid,
          "timeStamp": data.t.params.timeStamp,
          "nonceStr": data.t.params.nonceStr,
          "package": data.t.params.package,
          "signType": "MD5",
          "paySign": data.t.params.paySign
        }
        WeixinJSBridge.invoke ('getBrandWCPayRequest', params, (res) => {
            if(res.err_msg == "get_brand_wcpay_request:ok" ){
              if (typeof fn === 'function') {
                console.log('pay success')
                fn()
              }
            } else {
              cancelFn()
            }
        })
      }
    })
  }

